<template>
  <div class="right">
    <div class="top">
      <p class="title">{{ title }}</p>
      <p class="subtitle">{{ subtitle }}</p>
    </div>
    <div class="middle">
      <div class="item">
        <span class="icon icon-youxiang5 icons"></span>
        <el-tooltip
          :content="phoneTipText"
          placement="bottom-start"
          effect="light"
          v-model="phoneTip"
          manual
        >
          <input
            type="text"
            required
            v-model="phoneOrEmail"
            @input="inputInfo"
          />
        </el-tooltip>
        <span class="plese">邮箱/手机</span>
      </div>
      <div class="item" v-if="status != 'forget' || isSend">
        <span class="icon icon-mima7 icons"></span>
        <el-tooltip
          :content="pwdTipText"
          placement="bottom-start"
          effect="light"
          v-model="pwdTip"
          manual
        >
          <input
            :type="inputType"
            required
            v-model="password"
            @input="inputInfo"
            @click="pwdInput"
          />
        </el-tooltip>
        <span class="plese">
          {{ status == "forget" ? "验证码" : "密码" }}
        </span>
      </div>
      <div class="item" v-if="status == 'register'">
        <span class="icon icon-mima4 icons"></span>
        <el-tooltip
          content="两次输入密码不一致！"
          placement="bottom-start"
          effect="light"
          v-model="pwdAgainTip"
          manual
        >
          <input
            ref="pwdAgain"
            :type="inputType"
            required
            v-model="pwdAgain"
            @input="inputInfo"
          />
        </el-tooltip>
        <span class="plese">确认密码</span>
      </div>
    </div>
    <div class="bottom">
      <!-- 登录 -->
      <div v-if="status == 'login'">
        <el-button
          type="primary"
          :loading="false"
          :disabled="!loginEable"
          class="botton"
          @click="doLogin"
          >登录</el-button
        >
        <div class="text">
          <!-- <span class="span1" @click="changeStatus('forget')">忘记密码?</span> -->
          <span class="span2" @click="changeStatus('register')">创建账户</span>
        </div>
      </div>

      <!-- 注册 -->
      <div v-if="status == 'register'">
        <el-button
          type="primary"
          :loading="false"
          :disabled="!registerEable"
          class="botton"
          @click="doRegister"
          >创建账户</el-button
        >
        <div class="text">
          <span class="span2" @click="changeStatus('login')"
            >已有账户？
            <p>登录</p></span
          >
        </div>
      </div>
      <!-- 忘记密码 -->
      <!-- <div v-if="status == 'forget'">
        <div :class="isTwoBtn ? 'botton-container' : ''">
          <el-button
            type="primary"
            :loading="sendLoad"
            class="botton"
            @click="sendCode"
            :disabled="!sendEable"
            >{{ codeText }}</el-button
          >
          <el-button
            type="success"
            :loading="false"
            class="botton"
            v-show="isTwoBtn"
            :disabled="!verifyEnable"
            @click="loginByCode"
            >验证</el-button
          >
        </div>
        <div class="text">
          <span class="span2" @click="changeStatus('login')">返回</span>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script>
const isPhone = /^1[3|4|5|7|8][0-9]\d{8}$/;
const isEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
const isPwdOk = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d\S]{6,20}$/;
import service from "@/utils/request";

export default {
  name: "login",
  props: ["chooseType"],
  data() {
    return {
      inputType: "text",
      phoneTip: false,
      phoneTipText: "请输入正确格式的邮箱/手机！",
      pwdTip: false,
      pwdTipText: "密码是由数字、字母、组成的6-20位字符串",
      pwdAgainTip: false,
      isSend: false,
      status: "login",
      codeText: "发送验证码",
      phoneOrEmail: "",
      //8-20位，至少包含数字，大小写字母，特殊字符,
      phone: "",
      email: "",
      password: "",
      pwdAgain: "",
      isTwoBtn: false,
      //节流
      lastClick: 0,
      userId: "",
      sendLoad: false,
    };
  },

  watch: {
    phoneOrEmail() {
      if (isPhone.test(this.phoneOrEmail)) {
        this.phone = this.phoneOrEmail;
        this.email = "";
        this.phoneTip = false;
      } else if (isEmail.test(this.phoneOrEmail)) {
        this.email = this.phoneOrEmail;
        this.phone = "";
        this.phoneTip = false;
      } else {
        this.email = "";
        this.phone = "";
        this.phoneTip = this.phoneOrEmail == "" ? false : true;
        this.phoneTipText = "请输入正确格式的邮箱/手机！";
      }
    },
    password() {
      if (this.status == "forget") {
        this.pwdTipText = "请输入6位数字验证码";
        this.pwdTip = this.password.length < 6 && this.password.length > 0;
      } else {
        this.pwdTipText = "密码是由数字、字母、组成的6-20位字符串";
        this.pwdTip = !isPwdOk.test(this.password) && this.password != "";
      }
    },
    pwdAgain() {
      this.pwdAgainTip = this.password != this.pwdAgain && this.pwdAgain != "";
    },
  },
  computed: {
    //是否可以登录
    loginEable() {
      return (
        (isPhone.test(this.phone) || isEmail.test(this.email)) &&
        isPwdOk.test(this.password)
      );
    },
    //是否可以注册
    registerEable() {
      return (
        (isPhone.test(this.phone) || isEmail.test(this.email)) &&
        isPwdOk.test(this.password) &&
        this.password == this.pwdAgain
      );
    },
    //是否可以发送验证码
    sendEable() {
      return (
        (isPhone.test(this.phone) || isEmail.test(this.email)) &&
        (this.codeText == "发送验证码" || this.codeText == "重新发送")
      );
    },
    //是否可以验证,这里的验证等待修改
    verifyEnable() {
      return (
        (isPhone.test(this.phone) || isEmail.test(this.email)) &&
        this.password.length == 6
      );
    },
    title() {
      if (this.status == "login") {
        return "欢迎访问!";
      } else if (this.status == "register") {
        return "创建账户";
      } else if (this.status == "forget") {
        return "验证码登录";
      } else {
        return "出错了!";
      }
    },
    subtitle() {
      if (this.status == "login") {
        return "登录您的账户以继续!";
      } else if (this.status == "register") {
        return "请创建账户以继续使用我们的服务";
      } else if (this.status == "forget") {
        return "使用验证码以验证您的身份";
      } else {
        return "出错了!";
      }
    },
  },
  mounted() {
    if (this.chooseType) {
      this.status = this.chooseType;
    } else {
      this.status = "login";
    }
  },
  methods: {
    pwdInput() {
      if (this.status == "forget") {
        this.inputType = "number";
      } else {
        this.inputType = "password";
      }
    },
    //封装一下提示信息
    myNotify(type, title, message) {
      this.$notify({
        title: title,
        message: message,
        offset: 100,
        type: type,
        duration: 3000,
      });
    },
    //节流操作，防止高频点击
    checkClickTooMuch() {
      if (Date.now() - this.lastClick <= 2000) {
        this.myNotify("info", "提示", "操作太频繁,休息一下吧~~~");
        return true;
      }
      this.lastClick = Date.now();
      return false;
    },

    doLogin() {
      if (this.checkClickTooMuch()) {
        return;
      }
      const data = {
        userPhone: this.phone,
        userEmail: this.email,
        userPassword: this.password,
      };
      service
        .post("/user/login", data)
        .then((res) => {
          console.log("登录响应");
          switch (res.code) {
            case 200:
              localStorage.setItem("user", JSON.stringify(res.data));
              this.$store.dispatch("setUser", res.data); // 调用 Vuex action
              this.myNotify(
                "success",
                "登录成功！",
                `【${
                  res.data.userNickname ||
                  res.data.userEmail ||
                  res.data.userPhone
                }】欢迎使用,祝您使用愉快`
              );
              this.$router.push("/");
              break;
            case 201:
              this.phoneTipText = "账号不存在!";
              this.phoneTip = true;
              this.myNotify(
                "warning",
                "登录失败！",
                `用户【${this.phoneOrEmail}】不存在！`
              );
              break;
            case 202:
              this.pwdTip = true;
              this.pwdTipText = "密码错误!";
              this.myNotify(
                "warning",
                "登录失败！",
                `请再次核对您的密码是否正确！`
              );
              break;
            case 203:
              // 保存用户信息到 Vuex
              localStorage.setItem("user", JSON.stringify(res.data));
              this.$store.dispatch("setUser", res.data); // 调用 Vuex action
              this.myNotify("success", "登录成功！", `首次登录,请选择电影偏好`);
              this.$router.push("/chooseFavor");
              break;
            default:
              this.myNotify(
                "error",
                "系统错误！",
                `服务器开小差了，请稍后再试~~~`
              );
              break;
          }
        })
        .catch((error) => {
          this.myNotify("error", "系统错误！", `服务器开小差了，请稍后再试~~~`);
          console.error("请求出错:", error);
        });
    },

    doRegister() {
      if (this.checkClickTooMuch()) {
        return;
      }
      //点击注册,此时密码，确认密码，邮箱，手机都验证通过了
      const data = {
        userPhone: this.phone,
        userEmail: this.email,
        userPassword: this.password,
      };
      service
        .post("/user/register", data)
        .then((res) => {
          console.log("注册响应");
          ////console.log(res);
          switch (res.code) {
            case 200:
              this.myNotify("success", "注册成功！");
              this.status = "login";
              break;
            case 205:
              this.phoneTipText = "账号已存在!";
              this.phoneTip = true;
              this.myNotify(
                "warning",
                "注册失败！",
                `用户【${this.phoneOrEmail}】已存在！`
              );
              break;
            default:
              this.myNotify(
                "error",
                "系统错误！",
                `服务器开小差了，请稍后再试~~~`
              );
              break;
          }
        })
        .catch((error) => {
          this.myNotify("error", "系统错误！", `服务器开小差了，请稍后再试~~~`);
          console.error("系统错误:", error);
        });
    },
    //点击发送验证码之后
    sendCode() {
      this.sendLoad = true;
      this.codeText = "正在发送...";
      this.isSend = true;
      this.isTwoBtn = true;

      localStorage.removeItem("token");
      const data = {
        userPhone: this.phone,
        userEmail: this.email,
      };
      service
        .post("/login/sendCode", data, { timeout: 60000 })
        .then((res) => {
          console.log("发送验证码响应");
          ////console.log(res);
          if (res.code == 200) {
            this.myNotify(
              "success",
              "发送成功！",
              `验证码已发送到【${this.phoneOrEmail}】`
            );
            this.userId = res.data;
            this.sendLoad = false;
            let minutes = 60;
            this.codeText = `重新发送(${minutes})`;
            let timer = setInterval(() => {
              minutes--;
              this.codeText = `重新发送(${minutes})`;
              if (minutes <= 0) {
                this.codeText = `重新发送`;
                clearInterval(timer);
              }
            }, 1000);
          } else if (res.code == 201) {
            this.myNotify(
              "warning",
              "发送失败！",
              `用户【${this.phoneOrEmail}】不存在！`
            );
            this.phoneTipText = "账号不存在!";
            this.phoneTip = true;
            this.sendLoad = false;
            this.codeText = "重新发送";
          } else {
            this.sendLoad = false;
            this.myNotify("warning", "发送失败！", res.message);
            this.codeText = "重新发送";
            if (minutes > 0) {
              clearInterval(timer);
            }
          }
        })
        .catch((error) => {
          this.codeText = "重新发送";
          if (minutes > 0) {
            clearInterval(timer);
          }
          this.myNotify("error", "系统错误！", `服务器开小差了，请稍后再试~~~`);
          console.error("系统错误:", error);
        });
    },

    //这里处理验证码登录逻辑，此事件触发，条件都满足
    loginByCode() {
      if (this.checkClickTooMuch()) {
        return;
      }
      const data = {
        userId: this.userId,
        code: parseInt(this.password),
      };
      service
        .post("/login/byCode", data)
        .then((res) => {
          console.log("验证码登录响应");
          ////console.log(res);
          switch (res.code) {
            case 200:
              //保存用户信息
              localStorage.setItem("user", JSON.stringify(res.data));
              this.myNotify(
                "success",
                "登录成功！",
                `【${
                  res.data.userNickname ||
                  res.data.userEmail ||
                  res.data.userPhone
                }】欢迎使用,祝您使用愉快`
              );
              if (res.data.userType == 0) {
                this.$router.push({
                  path: "/admin",
                  query: { user: res.data },
                });
              } else {
                this.$router.push({ path: "/", query: { type: "code" } });
              }

              break;
            case 210:
              this.pwdTipText = res.message;
              this.pwdTip = true;
              this.myNotify("warning", "登录失败！", res.message);
              break;
            default:
              this.myNotify(
                "error",
                "系统错误！",
                `服务器开小差了，请稍后再试~~~`
              );
              break;
          }
        })
        .catch((error) => {
          this.myNotify("error", "系统错误！", `服务器开小差了，请稍后再试~~~`);
          console.error("系统错误:", error);
        });
    },
    //三个输入框的输入事件
    inputInfo(e) {},
    //登录，注册，忘记密码切换
    changeStatus(e) {
      this.phoneOrEmail = "";
      this.password = "";
      this.pwdAgain = "";
      this.status = e;
    },
  },
};
</script>
<style scoped lang="less">
.right {
  width: 32%;
  height: 100%;
  background-color: #ffffff;
  display: flex;
  justify-content: center;
  flex-direction: column;
  border-radius: 0 1.25rem 1.25rem 0;
  position: relative;

  .skip {
    position: absolute;
    bottom: 1rem;
    right: 1rem;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
      color: blue;
    }
  }

  & > * {
    margin-left: 3rem;
  }

  .top {
    height: 10%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .title {
      font-size: 1.875rem;
      color: #000000;
    }

    .subtitle {
      font-size: 1rem;
      color: #7a7a7a;
      margin-top: 0.2rem;
    }
  }

  .middle2 {
    height: 40%;
  }

  .middle {
    height: 32%;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;

    .item {
      height: 25%;
      width: 80%;
      display: flex;
      align-items: center;
      margin-bottom: 1rem;
      position: relative;

      .icons {
        position: absolute;
        left: 0;
        bottom: 0;
        font-weight: 700;
        display: block;
        height: 2.7rem;
        width: 2.7rem;
        border-radius: 0.6rem;
        color: #311884;
        text-align: center;
        line-height: 2.6rem;
        font-size: 1rem;
        background-color: #edebf5;
      }

      input {
        display: block;
        width: 70%;
        border: 0;
        border-bottom: 0.125rem solid rgba(0, 0, 0, 0.5);
        position: absolute;
        left: 3rem;
        bottom: 0;
        padding: 0.4rem 0.625rem;
        font-size: 0.9rem;
        font-weight: 700;
        outline: none;
      }

      .plese {
        font-size: 1rem;
        display: block;
        width: 70%;
        position: absolute;
        left: 3.8rem;
        bottom: 0.7rem;
        pointer-events: none;
        text-transform: uppercase;
        color: rgba(0, 0, 0, 1);
        transition: 0.5s;
      }

      input:valid ~ span,
      input:focus ~ span {
        color: #787876;
        transform: translateX(0) translateY(-1.1rem);
        font-size: 0.7rem;
        font-weight: 700;
        letter-spacing: 4px;
      }

      /deep/.line-input {
        .el-input__inner {
          border-radius: 0px;
          border-top-width: 0px;
          border-left-width: 0px;
          border-right-width: 0px;
          border-bottom-width: 1px;
          /*outline: medium;*/
        }
      }
    }

    .item:last-child {
      margin-bottom: 0;
    }
  }

  .bottom {
    width: 66%;
    margin-top: 1rem;

    .botton-container {
      display: flex;
      justify-content: space-between;
      width: 100%;
      transition: all 0.1s linear;

      .botton {
        width: 50%;
        height: 2.5rem;
        font-size: 1.2rem;
        background-color: #5bdd19;
        transition: width 0.1s linear;
        border-radius: 0.4rem;
      }

      .botton:disabled {
        background-color: #9abd88;
      }

      .botton:last-child {
        width: 40%;
        background-color: #3327dd;
      }

      .botton:disabled:last-child {
        width: 40%;
        background-color: #7b76bf;
      }
    }

    .botton {
      width: 100%;
      height: 2.5rem;
      background-color: #3327dd;
      font-size: 1.2rem;
      transition: width 0.1s linear;
      border-radius: 0.4rem;
    }

    .botton:disabled {
      background-color: #7b75c9;
    }

    .text {
      margin-top: 0.2rem;
      width: 100%;

      span:hover {
        text-decoration: underline;
        color: blue;
      }

      span {
        font-size: 1rem;
        cursor: pointer;
      }

      .span1 {
        float: left;
      }

      .span2 {
        float: right;

        p {
          cursor: pointer;
          display: inline;
          color: rgb(25, 148, 230);
          color: blue;
        }
      }
    }
  }
}
</style>

userBirthday: "2002-07-25"
userEmail: ""
userGender: ""
_id: 11110038
userIntroduce: ""
userLastloginTime: ""
userModifyTime: ""
userNickname: ""
userPassword: ""
userPhone: ""
userProfileUrl: "a445be96-88ac-4b64-b37b-742cbd61704a.jpg"
userRealname: ""
userRegisterTime: "2024-07-02 14:33:07"
